package com.skyable.account.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.skyable.account.entity.SysUser;
import com.skyable.account.handler.sentinel.UserSentinelHandler;
import com.skyable.account.service.IUserService;
import com.skyable.common.common.ResponseResult;
import com.skyable.common.common.ServiceResult;
import com.skyable.common.exceptions.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

/**
 * @author GaoYuan
 * @title: UserController
 * @projectName spring-cloud-demo
 * @description: TODO
 * @date 2021/3/714:32
 */
@ApiIgnore
@RestController
@RequestMapping(value = "/user")
@RefreshScope
@Slf4j
public class TestController {

    @Value("${server.port}")
    private Integer serverPort;
    @Value("${server.version}")
    private String version;
    @Autowired
    private IUserService userService;

    @GetMapping(value = "/view/port")
    public ResponseResult port() {
        log.info("port:" + serverPort);
        return ResponseResult.success(serverPort);
    }

    @GetMapping(value = "/view/version")
    public ResponseResult version(HttpServletRequest request) {
        String user = request.getHeader("User");
        log.info("user:" + user);
        return ResponseResult.success(version);
    }

    @GetMapping(value = "/view/sentinel/{id}")
    @SentinelResource(value = "sentinel", blockHandlerClass = UserSentinelHandler.class, blockHandler = "sentinelBlock",
            fallbackClass = UserSentinelHandler.class, fallback = "sentinelFallBack")
    public ResponseResult sentinel(@PathVariable Integer id) {
        if(id == 0) {
            throw new BusinessException("业务处理失败", 500);
        }
        return ResponseResult.success("sentinel success");
    }

    @PostMapping(value = "/insert/{name}")
    public ResponseResult createUser(@PathVariable String name) {
        SysUser sysUser = new SysUser();
        sysUser.setUsername(name);
        sysUser.setPassword("123456");
        sysUser.setCreateTime(new Date());
        sysUser.setUpdateTime(new Date());
        ServiceResult<SysUser> serviceResult = userService.insertUser(sysUser, null);
        if(!serviceResult.getSuccess()) {
            return ResponseResult.error(serviceResult.getCode(),serviceResult.getMessage());
        }
        return ResponseResult.success(serviceResult.getResult());
    }
}
